# search.py
# ---------
# Licensing Information:  You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
# 
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).


"""
In search.py, you will implement generic search algorithms which are called by
Pacman agents (in searchAgents.py).
"""

import util


class SearchProblem:
    """
    This class outlines the structure of a search problem, but doesn't implement
    any of the methods (in object-oriented terminology: an abstract class).

    You do not need to change anything in this class, ever.
    """

    def getStartState(self):
        """
        Returns the start state for the search problem.
        """
        util.raiseNotDefined()

    def isGoalState(self, state):
        """
          state: Search state

        Returns True if and only if the state is a valid goal state.
        """
        util.raiseNotDefined()

    def getSuccessors(self, state):
        """
          state: Search state

        For a given state, this should return a list of triples, (successor,
        action, stepCost), where 'successor' is a successor to the current
        state, 'action' is the action required to get there, and 'stepCost' is
        the incremental cost of expanding to that successor.
        """
        util.raiseNotDefined()

    def getCostOfActions(self, actions):
        """
         actions: A list of actions to take

        This method returns the total cost of a particular sequence of actions.
        The sequence must be composed of legal moves.
        """
        util.raiseNotDefined()


def tinyMazeSearch(problem):
    """
    Returns a sequence of moves that solves tinyMaze.  For any other maze, the
    sequence of moves will be incorrect, so only use this for tinyMaze.
    """
    from game import Directions
    s = Directions.SOUTH
    w = Directions.WEST
    return [s, s, w, s, w, w, s, w]


def depthFirstSearch(problem: SearchProblem):
    """
    Search the deepest nodes in the search tree first.

    Your search algorithm needs to return a list of actions that reaches the
    goal. Make sure to implement a graph search algorithm.

    To get started, you might want to try some of these simple commands to
    understand the search problem that is being passed in:

    print("Start:", problem.getStartState())
    print("Is the start a goal?", problem.isGoalState(problem.getStartState()))
    print("Start's successors:", problem.getSuccessors(problem.getStartState()))
    """
    "*** YOUR CODE HERE ***"
    from util import Stack
    closed = []
    fringe = Stack()
    actionLink = {}

    # 虚拟根结点
    startState = problem.getStartState()
    fringe.push(startState)
    actionLink[startState] = None
    while True:
        if fringe.isEmpty():
            return []
        state = fringe.pop()
        if problem.isGoalState(state):
            # 解析路径
            action = parseAction(state, actionLink)
            return action
        if state not in closed:
            closed.append(state)
            successors = problem.getSuccessors(state)
            for childState, direction, _ in successors:
                if childState not in closed:
                    fringe.push(childState)
                    # 因为是dfs,后来的总比前面的优先级要高.前面的搞不了,所以才轮到后面的
                    actionLink[childState] = (state, direction)


def parseAction(state, actionLink, col=1):
    """针对特定数据结构的解析路径"""
    actionList = []
    actionUnit = actionLink[state]
    while actionUnit is not None:
        actionList.append(actionUnit[col])
        state = actionUnit[0]
        actionUnit = actionLink[state]
    actionList.reverse()
    return actionList


def breadthFirstSearch(problem: SearchProblem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    from util import Queue
    startState = problem.getStartState()
    stateQ = Queue()
    actionD = {startState: None}
    closed = []
    stateQ.push(startState)

    while True:
        if stateQ.isEmpty():
            return []
        state = stateQ.pop()
        if problem.isGoalState(state):
            action = parseAction(state, actionD)
            return action
        # 检查节点是否已经过扩展
        if state not in closed:
            closed.append(state)
            successors = problem.getSuccessors(state)
            for childState, direction, _ in successors:
                if childState not in closed:
                    stateQ.push(childState)
                    # 这里一定要加判断,因为是BFS搜索,先建立父子映射的优先级更高
                    if childState not in actionD:
                        actionD[childState] = (state, direction)


def uniformCostSearch(problem: SearchProblem):
    """Search the node of least total cost first."""
    "*** YOUR CODE HERE ***"
    # 初始化fringe_stack和closed_list
    from util import PriorityQueue

    closed = []
    fringe = PriorityQueue()
    actionLink = {}  # 映射是 state -> 父state,父节点到此节点的方向
    costDict = {}  # 此节点的总代价

    # 虚拟根结点
    Start = problem.getStartState()
    fringe.push(Start, 0)
    actionLink[Start] = None
    costDict[Start] = 0
    while True:
        if fringe.isEmpty():
            return []
        state = fringe.pop()

        if problem.isGoalState(state):
            # 构造路径
            action = parseAction(state, actionLink)
            return action
        if state not in closed:
            closed.append(state)
            successors_n = problem.getSuccessors(state)
            for childState, direction, cost in successors_n:
                if childState in costDict:
                    cost_t = costDict[state] + cost
                    cost_c = costDict[childState]
                    if cost_t < cost_c:
                        costDict[childState] = cost_t
                        actionLink[childState] = (state, direction)
                else:
                    costDict[childState] = costDict[state] + cost
                    actionLink[childState] = (state, direction)
                fringe.update(childState, costDict[childState])


def nullHeuristic(state, problem=None):
    """
    A heuristic function estimates the cost from the current state to the nearest
    goal in the provided SearchProblem.  This heuristic is trivial.
    """
    return 0


def aStarSearch(problem: SearchProblem, heuristic=nullHeuristic):
    """Search the node that has the lowest combined cost and heuristic first."""
    "*** YOUR CODE HERE ***"
    from util import PriorityQueue

    closed = []
    fringe = PriorityQueue()
    actionLink = {}  # 映射是 state -> 父state,父节点到此节点的方向
    costDict = {}  # 映射是 state -> 到此节点的总实际代价

    # 虚拟根结点
    startState = problem.getStartState()
    heuristicVal = 0 + heuristic(startState, problem)
    fringe.push(startState, heuristicVal)
    actionLink[startState] = None
    costDict[startState] = 0
    while True:
        if fringe.isEmpty():
            return []
        state = fringe.pop()

        if problem.isGoalState(state):
            # 构造路径
            action = parseAction(state, actionLink)
            return action
        if state not in closed:
            closed.append(state)
            successors_n = problem.getSuccessors(state)
            for childState, direction, cost in successors_n:
                if childState in costDict:
                    cost_t = costDict[state] + cost
                    cost_c = costDict[childState]
                    if cost_t < cost_c:
                        costDict[childState] = cost_t
                        actionLink[childState] = (state, direction)
                else:
                    costDict[childState] = costDict[state] + cost
                    actionLink[childState] = (state, direction)
                heuristicVal = costDict[childState] + heuristic(childState, problem)
                fringe.update(childState, heuristicVal)


# Abbreviations
bfs = breadthFirstSearch
dfs = depthFirstSearch
astar = aStarSearch
ucs = uniformCostSearch
